import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox

import os


class RonlyEntry(tk.Frame):
    def __init__(self, root, defaulttext="", width: int = 10, **kwargs):
        super(RonlyEntry, self).__init__(root, **kwargs)
        self.vtext = tk.StringVar(self)
        self.entry = tk.Entry(self, textvariable=self.vtext, width=width, validatecommand=lambda: False)
        self.entry.update()
        self.entry.configure(validate="key")

        self.set(defaulttext)
        self.entry.pack()

    def set(self, newtext):
        self.vtext.set(newtext)
        self.entry.configure(validate="key")

    def get(self):
        text = self.vtext.get()
        self.entry.configure(validate="key")
        return text


class DynamicDropMenu(tk.Frame):
    def __init__(self, frameroot, defaultstr="请选择出战的干员", menulist=["切利妮娜", "蕾缪安", "拉普兰德"],
                 command=lambda: print("动态菜单按键被按下"), buttonlabel="确认", buttonloc="e", width=20,
                 state="readonly", buttonstate = True):
        super(DynamicDropMenu, self).__init__(frameroot)
        self.v = tk.StringVar(frameroot)
        self.ddm = ttk.Combobox(self, width=width, state=state, textvariable=self.v)
        self.v.set(defaultstr)
        self.resetmenu(defaultstr, menulist)
        self.style = ttk.Style()
        # self.style.configure("DynamicDropMenu.TButton", width=5 + len(buttonlabel), height=1, background='ghostwhite')
        self.checkbutton = tk.Button(self, text=buttonlabel, command=command, width=5 + len(buttonlabel), height=1)

        self.ddm.grid(row=0, column=0, sticky="ew")
        if buttonstate :
            self.checkbutton.grid(row=0, column=1, sticky="e")

    def resetmenu(self, newdefaultstr: str, newlist: list):
        self.ddm["value"] = newlist[:]
        self.v.set(newdefaultstr)

    def getvalue(self):
        return self.ddm.get()

    def resetcommand(self, command=print):
        if callable(command):
            self.checkbutton.configure(command=command)


class SubWindow:
    def __init__(self, root, size="600x400", title="tk", **kwargs):
        # self.l = tk.Label(self)
        # self.menu = tk.Menu(self, tearoff= False)
        # self.filemenu = tk.Menu(self, tearoff= False)
        # self.filemenu.add_command(label="打开")
        # self.filemenu.add_command(label="保存")
        # self.filemenu.add_separator()
        # self.filemenu.add_command(label="退出", command=lambda :self.withdraw())
        # self.menu.add_cascade(label="文件",menu=self.filemenu)
        # self["menu"] = self.menu
        self.frame = tk.Toplevel(root, **kwargs)
        self.state = self.frame.state()
        self.frame.title(title)
        self.menu = tk.Menu()
        self.close()

        # 重写退出键
        self.frame.protocol(name="WM_DELETE_WINDOW", func=self.close)
        self.frame.geometry(size)

        self.frame['menu'] = self.menu

    def open(self):
        self.frame.deiconify()
        self.state = self.frame.state()

    def close(self):
        self.frame.withdraw()
        self.state = self.frame.state()

    def add_menu(self, menu=None, name="新建菜单"):
        self.menu.add_cascade(label=name, menu=menu)


class DataTable(tk.Frame):
    def __init__(self, master, rindex: list, cindex: list, values, maxheight=4095, minwidth=200):
        super().__init__(master)
        self.pack()  # frame加入root
        self.tableColumns = cindex
        self.actualheight = len(values)
        self.maxheight = maxheight
        self.inshowheight = int(maxheight)
        self.excess = False #表格尺寸是否过大
        self.minwidth = minwidth
        if len(values) > maxheight:
            self.excess = True
            tk.messagebox.showinfo("超出预览限制",
                                   f"表格大小超出预览限制，将仅预览表格的\n前{self.inshowheight}行与后{self.inshowheight}行。")
            self.focus_force()
            blank = []
            for i in cindex:
                blank.append('......')
            self.tableValues = values[0:self.inshowheight] + values[-self.inshowheight:]
            self.tableValues.insert(self.inshowheight, blank)
            self.tableValues.insert(self.inshowheight, blank)
            self.tableValues.insert(self.inshowheight, blank)
            self.index = rindex[0:self.inshowheight] + ['......'] + ['......'] + ['......'] + rindex[
                                                                                              -self.inshowheight:]
            self.height = 2 * self.inshowheight + 3

        else:
            self.tableValues = values
            self.index = rindex
            self.height = self.actualheight
        # 设置滚动条
        xscroll = ttk.Scrollbar(self, orient="horizontal")
        yscroll = ttk.Scrollbar(self, orient="vertical")
        xscroll.pack(side='bottom', fill='x')
        yscroll.pack(side='right', fill='y')

        self.table = ttk.Treeview(
            master=self,  # 父容器
            columns=self.tableColumns,  # 列标识符列表
            height=30,  # 表格显示的行数
            show='headings',  # 隐藏首列
            style='Treeview',  # 样式
            xscrollcommand=xscroll.set,  # x轴滚动条
            yscrollcommand=yscroll.set  # y轴滚动条
        )

        xscroll.config(command=self.table.xview)
        yscroll.config(command=self.table.yview)
        self.table.pack()  # TreeView加入frame

        self.table.heading(column="#0", text="行序号", anchor="center")  # 设置#0列表头
        self.table.column(column="#0", minwidth=self.minwidth, stretch=False, anchor="center")
        for i in range(len(self.tableColumns)):
            self.table.heading(column=self.tableColumns[i], text=self.tableColumns[i], anchor="center")  # 设置除#0列以外的表头
            self.table.column(self.tableColumns[i], minwidth=self.minwidth, anchor="center", stretch=False)  # 设置列
        for i in range(len(self.index)):
            self.table.insert('', 'end', text=str(self.index[i]), values=self.tableValues[i])

    def movefocus(self, target=[0, 0]):
        if self.excess:
            if target[0] < self.inshowheight:
                pass
            elif self.actualheight - self.inshowheight < target[0] < self.actualheight:
                target[0] = self.height - (self.actualheight - target[0])
            else:
                tk.messagebox.showinfo("提示", f"该行已被隐藏")
                self.focus_force()

        if target[0] <= self.height:
            target[0] = str(hex(int(target[0]) + 1)).upper()[2:]
            target[0] = 'I000'[0:4 - len(target[0])] + target[0]
            self.table.see(target[0])
            self.table.selection_set(target[0])
            self.table.xview(self.minwidth * (target[1] - 1) - 100)
        else:
            print("超出大小")
            tk.messagebox.showinfo("超出预览限制", f"查找范围超出限制\n行标应小于{self.actualheight}")
            self.focus_force()

        return self.table.focus()


if __name__ == "__main__":
    root = tk.Tk()
    root.title("PRTS")
    root.geometry("240x150")

    # tk.Label(root, text="基于OptionMenu的下拉菜单示例").pack(pady=10)

    oldlist = ["史尔特尔", "艾雅法拉", "伊芙利特"]
    newlist = ["克洛斯", "芬", "芙蓉"]

    f = tk.Frame(root)

    ddl = DynamicDropMenu(f, defaultstr="叙拉古游客组", menulist=oldlist, command=lambda: print(ddl.getvalue()),
                          buttonloc="e")
    ddl.grid(row=0, sticky="ew")
    setbutton = ttk.Button(f, text="更新干员名单", width=20, command=lambda: ddl.resetmenu("预备行动组A1", newlist))
    setbutton.grid(row=1, sticky="ew")
    f.pack()

    # f1 = FFChooser(f, mood='file')
    # f2 = FFChooser(f, mood='folder')
    # f1.grid(row=3, sticky="ew")
    # f2.grid(row=4, sticky="ew")
    # ttk.Button(f, text="输出选中的文件", command=lambda: print(f1.selected())).grid(row=6, sticky="ew")

    root.mainloop()
